<?php

class DashboardPage extends MemberOverviewPage {
	private static $has_many = array(
		'Widgets' => 'Widget.DashboardPage'
	);

	function getCMSFields(){
		$fields = parent::getCMSFields();

		$adder = new GridFieldAddNewMultiClass();

		if(is_array($this->config()->get("allowed_widgets"))){
			$adder->setClasses($this->config()->get("allowed_widgets"));
		}

		$config = GridFieldConfig_RecordEditor::create()
			->removeComponentsByType("GridFieldAddNewButton")
			->addComponent($adder)
			->addComponent(new GridFieldOrderableRows());

		$fields->addFieldToTab("Root.Main",
			GridField::create('Widgets','Widgets',$this->Widgets())
				->setConfig($config)
			,"Content"
		);
		$fields->removeByName("Content");
		return $fields;
	}

}

class DashboardPage_Controller extends MemberOverviewPage_Controller {
    function init(){
        parent::init();
        Requirements::css('member/css/DashboardPage.css');
    }
}

class DashboardPageWidget extends DataExtension {
	private static $has_one = array(
		'DashboardPage' =>  'DashboardPage'
	);
    
    private static $many_many = array(
        'Groups' => 'Group'
    );
    
    function updateCMSFields(FieldList $fields){
        $groupsMap = array();
        foreach(Group::get() as $group) {
            // Listboxfield values are escaped, use ASCII char instead of &raquo;
            if($group->IsDistributorGroup){
            	$groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
           	}
        }
        asort($groupsMap);
        $field = ListboxField::create('Groups', _t('DashboardPageWidget.ALLOWED_GROUP', 'Allowed Group'))
        ->setMultiple(true)
        ->setSource($groupsMap)
        ->setAttribute(
            'data-placeholder', 
            'Assign group'
        );
		$fields->removeByName('Groups');
        $fields->push($field);
    }
    
    function canShow($member = null){
        if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
            $member = Distributor::currentUserID();
        }
        
        if(Permission::checkMember($member, "ADMIN")) return true;
        
        if($member && is_numeric($member)) $member = DataObject::get_by_id('Member', $member);
        if($member && $member->inGroups($this->owner->Groups())){
            return true;
        }
        
        return false;
    }
}